<?php
/**
 * MVC_ORM
 * @version 1.0
 * date: 07May2008
 *  
 * @author ThanhNV
 * email: sony_k48@yahoo.com
 * 
 * @desc Object-Relational Mapping (ORM)
 * @desc An ORM is made up of objects that give access to data and keep business rules within themselves.
 */

class MVC_ORM {
	private $oLink;
	private $bPersistent = false;
	
	public function __construct(){
		$this->db_connect();	
	}
	
	public function db_connect($host = NULL, $database = NULL, $user = NULL, $password = NULL, $port = NULL, $type = NULL){
		if ( defined( DB_PERSISTENT ) )
		{
			$this->bPersistent = DB_PERSISTENT;
		}

		if (is_null($host))
		{
			$host = DB_HOST;
		}

		if (is_null($database))
		{
			$database = DB_NAME;
		}

		if (is_null($user))
		{
			$user = DB_USER;
		}

		if (is_null($password))
		{
			$password = DB_PASS;
		}

		if (is_null($port))
		{
			$port = DB_PORT;
		}

		if (is_null($type))
		{
			$type = DB_TYPE;
		}
		
		if ($this->bPersistent) {
			$this->oLink = mysql_pconnect($host, $user, $password);
		} else {
			$this->oLink = mysql_connect($host, $user, $password);
		}

		if ($this->oLink) { 
			mysql_select_db($database);
		}
	}
	
	public function db_error($query, $errno, $error) {
		die('<font color="#000000"><b>' . $errno . ' - ' . $error . '<br><br>' . $query . '<br><br><small><font color="#ff0000">[TEP STOP]</font></small><br><br></b></font>');
	}
	
	public function db_query($sSql){
    	$result = mysql_query($sSql, $this->oLink);
    	return $result;
	}
	
	public function db_fetch_array($db_query) {
		return @mysql_fetch_array($db_query, MYSQL_ASSOC);
	}

	public function db_num_rows($db_query) {
		return @mysql_num_rows($db_query);
	}

	public function db_data_seek($db_query, $row_number) {
		return mysql_data_seek($db_query, $row_number);
	}

	public function db_insert_id() {
		return mysql_insert_id($this->oLink);
	}

	public function db_free_result($db_query) {
		return mysql_free_result($db_query);
	}

	public function db_fetch_fields($db_query) {
		return mysql_fetch_field($db_query);
	}
	
	public function db_prepare_output($data){
		if(is_array($data)){
			foreach ($data as $key=>$value){
				$data[$key] = stripslashes($value);
			}
			return $data;
		}else{
			$data = stripslashes($data);
			return $data;
		}
	}
	public function db_prepare_input($data){
		if(is_array($data)){
			foreach ($data as $key=>$value){
				$data[$key] = addslashes($value);
			}
			return $data;
		}else{
			$data = addslashes($data);
			return $data;
		}
	}
}
?>